<template>
    <view>
        <view v-if="id && isLoad === null" class="margin-top load notexist text-l text-grey"></view>
        <view v-if="id && isLoad === false" class="margin-top load loading text-l text-grey"></view>
        <block v-if="isAdmin && isLoad">
            <view class="main-admin">
                <!-- parse <include src="../add/admin_meet_form_tpl.wxml"/> -->
                <block>
                    <view class="form-box shadow">
                        <view class="form-group">
                            <view class="title must">老师名称</view>
                            <input placeholder="请输入老师的名称" placeholder-class="phc" v-model="formTitle" :focus="formTitleFocus" maxlength="50" />
                        </view>
                        <view v-if="formTitleFocus" class="hint-desc error">{{ formTitleFocus }}</view>

                        <view v-if="cateIdOptions.length > 1 && isAdmin" class="form-group arrow" id="formCateId">
                            <view class="title must">分类</view>
                            <cmpt-picker
                                id="cate-picker"
                                :sourceData="cateIdOptions"
                                @select="url($event, { type: 'picker', item: 'formCateId', tagId: 'cate-picker' })"
                                data-type="picker"
                                data-item="formCateId"
                                :item="formCateId"
                            ></cmpt-picker>
                        </view>
                        <view v-if="formCateIdFocus" class="hint-desc error">{{ formCateIdFocus }}</view>

                        <view class="form-group" v-if="isAdmin">
                            <view class="title must">
                                排序号
                                <text class="text-grey text-normal margin-left-xs">(小的先显示)</text>
                            </view>
                            <input placeholder="排序号，小的先显示" type="number" placeholder-class="phc" v-model="formOrder" :focus="formOrderFocus" maxlength="4" />
                        </view>
                        <view v-if="formOrderFocus" class="hint-desc error">{{ formOrderFocus }}</view>

                        <view class="form-group" id="formCancelSet">
                            <view class="title must">取消设置</view>
                            <cmpt-picker mark="cancelSet" style="flex: 1" :item.sync="formCancelSet" sourceDataStr="0=不可取消,1=随时可取消,2=仅开始前可取消" />
                        </view>
                        <view v-if="formCancelSetFocus" class="hint-desc error">{{ formCancelSetFocus }}</view>
                    </view>

                    <view id="formDaysSet" class="form-box shadow" style="background-color: #fef2ce">
                        <view @tap="url" :data-url="'../time/' + (isAdmin ? 'admin' : 'work') + '_meet_time'" class="form-group arrow">
                            <view class="title must">预约时段排期设置</view>
                            <view v-if="formDaysSet.length" class="form-text text-red text-bold">{{ formDaysSet.length }}天可约</view>
                            <view v-else class="form-text text-orange">请配置可预约时段</view>
                        </view>
                        <view v-if="formDaysSetFocus" class="hint-desc error">{{ formDaysSetFocus }}</view>
                    </view>

                    <view id="formPhone" class="form-box shadow">
                        <view class="form-group">
                            <view class="title must">老师登录手机</view>
                            <input maxlength="11" type="number" placeholder="请填写登录手机号码" v-model="formPhone" :focus="formPhoneFocus" />
                        </view>
                        <view v-if="formPhoneFocus" class="hint-desc error">{{ formPhoneFocus }}</view>

                        <view class="form-group text-orange" v-if="isAdmin && isEdit">
                            <text class="icon-info" style="font-size: 24rpx">不修改密码则保持以下为空</text>
                        </view>
                        <view class="form-group">
                            <view class="title must">老师登录密码</view>
                            <input maxlength="30" placeholder="请填写登录密码" v-model="formPassword" :focus="formPasswordFocus" />
                        </view>
                        <view v-if="formPasswordFocus" class="hint-desc error">{{ formPasswordFocus }}</view>
                    </view>

                    <view class="form-box shadow margin-top-xs">
                        <cmpt-form-show
                            id="cmpt-form"
                            mark="cmpt-form"
                            source="admin"
                            :isCacheMatch="false"
                            :fields="fields"
                            :forms="formForms"
                            :isDefMatch="id ? false : true"
                        ></cmpt-form-show>
                    </view>

                    <view class="form-box shadow" v-if="isAdmin">
                        <view class="form-group">
                            <view class="title must">
                                预约用户填写数据项目
                                <text class="text-grey text-normal">(共{{ formJoinForms.length }}个字段)</text>
                            </view>
                        </view>
                        <cmpt-form-set id="form-set" @formset="bindJoinFormsCmpt($event, { tagId: 'form-set' })" :fields="formJoinForms" />
                    </view>
                </block>

                <button @tap="bindFormEditSubmit" class="btn-admin margin-top-l">保存</button>
            </view>
        </block>
    </view>
</template>

<script>
import cmptFormSet from '@/cmpts/public/form/form_set/form_set_cmpt';
import cmptFormShow from '@/cmpts/public/form/form_show/form_show_cmpt';
import cmptPickerTime from '@/cmpts/public/picker_time/picker_time_cmpt';
import cmptPickerMulti from '@/cmpts/public/picker_multi/picker_multi_cmpt';
import AdminBiz from '@/utils/comm/biz/admin_biz.js';
import pageHelper from '@/utils/helper/page_helper.js';
import PublicBiz from '@/utils/comm/biz/public_biz.js';
import cloudHelper from '@/utils/helper/cloud_helper.js';
import timeHelper from '@/utils/helper/time_helper.js';
import validate from '@/utils/helper/validate.js';
import AdminMeetBiz from '@/utils/biz/admin_meet_biz.js';
import projectSetting from '@/utils/public/project_setting.js';
const api = require('@/api/adminapi.js');
export default {
    components: {
        cmptFormSet,
        cmptFormShow,
        cmptPickerTime,
        cmptPickerMulti
    },
    data() {
        return {
            isLoad: false,
            isEdit: true,
            formTitle: '',
            formCateId: 1,
            formOrder: '',
            formCancelSet: '',
            formPhone: '',
                formForms: [],
                formDaysSet: [],
                formJoinForms: [],
            id: '',
            isAdmin: true,
            formTitleFocus: null,
            cateIdOptions: null,
            formCateIdFocus: null,
            formOrderFocus: null,
            formCancelSetFocus: null,
            formDaysSetFocus: null,
            formPhoneFocus: null,
            formPassword: '',
            formPasswordFocus: null,
                fields: []
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        if (!AdminBiz.isAdmin(this)) {
            return;
        }
        if (!pageHelper.getOptions(this, options)) {
            return;
        }
        uni.setNavigationBarTitle({
            title: projectSetting.MEET_NAME + '-设置'
        });
        this.setData(await AdminMeetBiz.initFormData()); // 初始化表单数据
        await this.loadDetailFun();
        console.log('最终的this.formCateId:', this.formCateId);
        console.log('类型:', typeof this.formCateId);
        console.log('this.cateIdOptions:', this.cateIdOptions);
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: async function () {
        await this.loadDetailFun();
        uni.stopPullDownRefresh();
    },
    methods: {
        loadDetailFun: async function () {
            let id = this.id;
            if (!id) {
                return;
            }
            let params = {
                id
            };
            let opt = {
                title: 'bar'
            };
            let meet = await api.getAminTeacherInfo(params);
            // let meet = await cloudHelper.callCloudData('admin/meet_detail', params, opt);
            if (!meet) {
                this.setData({
                    isLoad: null
                });
                return;
            }
            console.log('meet', meet);
            console.log('meet.data:', meet.data);
            
            // 判断数据结构，可能有嵌套
            let meetData = meet.data || meet;
            console.log('meetData:', meetData);
            console.log('meetData.cateId:', meetData.cateId);
            console.log('meetData.type:', meetData.type);
            
            // 确定正确的分类字段名
            let cateId = meetData.cateId || meetData.type || meetData.categoryId || meetData.category;
            console.log('使用的cateId:', cateId);
            
            this.setData({
                isLoad: true,
                // 表单数据
                formTitle: meetData.title,
                formCateId: cateId,
                formOrder: meetData.order,
                formCancelSet: meetData.cancelSet,
                formPhone: meetData.phone,
                formForms: meetData.forms || [],
                formDaysSet: meetData.daysSet || [],
                formJoinForms: meetData.joinForms || []
            });
            console.log('setData后的formCateId:', this.formCateId);
        },

        bindJoinFormsCmpt: function (e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            this.setData({
                formJoinForms: e.detail
            });
        },

        bindFormEditSubmit: async function () {
            pageHelper.formClearFocus(this);
            if (!AdminBiz.isAdmin(this)) {
                return;
            }
            let data = this;
            if (data.formDaysSet.length <= 0) {
                pageHelper.anchor('formDaysSet', this);
                return pageHelper.formHint(this, 'formDaysSet', '请配置「可预约时段」');
            }
            if (data.formJoinForms.length <= 0) {
                return pageHelper.showModal('请至少设置一项「预约用户填写数据项目」');
            }
            data = validate.check(data, AdminMeetBiz.CHECK_FORM, this);
            if (!data) {
                return;
            }
            let forms = this.zpSelectComponent('#cmpt-form').getForms(true);
            if (!forms) {
                return;
            }
            data.forms = forms;
            data.cateName = AdminMeetBiz.getCateName(data.cateId);
            try {
                let meetId = this.id;
                data.id = meetId;
                api.updateTeacherInfo(data).then(res => {
                    console.log('res', res);
                });
                // 先修改，再上传
                // await cloudHelper.callCloudSumbit('admin/meet_edit', data);

                // 图片
                // await cloudHelper.transFormsTempPics(forms, 'meet/', meetId, 'admin/meet_update_forms');
                // let callback = async function () {
                //     // 更新列表页面数据
                //     let node = {
                //         MEET_TITLE: data.title,
                //         MEET_CATE_NAME: data.cateName,
                //         MEET_DAYS_SET: data.daysSet,
                //         MEET_JOIN_FORMS: data.joinForms,
                //         MEET_EDIT_TIME: timeHelper.time('Y-M-D h:m:s'),
                //         leaveDay: AdminMeetBiz.getLeaveDay(data.daysSet)
                //     };
                //     pageHelper.modifyPrevPageListNodeObject(meetId, node);
                //     uni.navigateBack();
                // };
                pageHelper.showSuccToast('编辑成功', 2000, callback);
            } catch (err) {
                console.log('CatchClause', err);
                console.log('CatchClause', err);
                console.log(err);
            }
        },

        url: function (e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            pageHelper.url(e, this);
        }
    }
};
</script>
<style>
@import './admin_meet_edit.css';
</style>
